package cn.rtplay.esp32camcar;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cn.rtplay.esp32camcar.databinding.FragmentSteeringWheelBinding;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class SteeringWheelFragment extends Fragment {
    private final String TAG = "SteeringWheelFragment";

    private FragmentSteeringWheelBinding mViewBinding;
    private final int mForeground;
    private ESP32UDPService mESP32UDPService;

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            LogUtil.v(TAG, "onServiceConnected in");
            mESP32UDPService = ((ESP32UDPService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mESP32UDPService = null;
        }
    };

    public SteeringWheelFragment(int style) {
        // Required empty public constructor
        if (style == UserData.VALUE_STEERING_WHEEL_STYLE_1) {
            mForeground = R.drawable.sw1;
        } else {
            mForeground = R.drawable.sw2;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LogUtil.v("SteeringWheelFragment", "onCreateView");
        // Inflate the layout for this fragment
        mViewBinding = FragmentSteeringWheelBinding.inflate(inflater, container, false);
//        mViewBinding.swSeekbar.setLimitAngle(540, -540);
        mViewBinding.swSeekbar.setListener(level -> {
            LogUtil.d("SteeringWheelFragment", "OnProgressChanged:" + level);
            if (mESP32UDPService.getChargingState() == ESP32UDPService.CHARGING_STATUS_NOT_CHARGING) {
                mESP32UDPService.setDirectionAngle(level * 4 / 54);
            }
        });
        mViewBinding.swSeekbar.setForeground(mForeground);
        Intent esp32ServiceIntent = new Intent(getActivity(), ESP32UDPService.class);
        if (getActivity() != null) {
            getActivity().bindService(esp32ServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }

        return mViewBinding.getRoot();
    }
}